Ext.define('AmpleHarvest.objects.search.querypanel.form.AbstractSearchForm',
{
   extend            : 'Ext.form.Panel',
   alias          :
   [
      'widget.ampleharvest-objects-search-form-abstractsearchform'
   ],
   stateId           : "Search_Window",
   frame          : true,
   title          : "SearchTEST",
   collapsible       : false,
   //width           : 315,
   scroll            : 'vertical',
   autoScroll:true,
   //collapseDirection  : "left",
   m_str_SourceGUID  : "",
   m_str_CurQuery    : "",
   g_arr_Requests    : [],
   requires       :
   [
         "Ext.button.Button",

         "AmpleHarvest.eventHandler.cWindowEvents"
   ],
   statics           :
   {
      C_STR_DATATYPE_DATE     : "date",
      C_STR_DATATYPE_VALUE : "value"
   },
   bubbleEvents      :
   [
      'statesave'
   ],

   initComponent     : function()
   {
      var obj_This = this;

      //Create buttons and then the next three buttons
      this.buttons = [];
      
      //Create button 1 - Save Query
      this.m_obj_Save_Query = Ext.create("Ext.button.Button",
      {
         text     : 'Save Query',
         disabled : true,
         scope    : obj_This,
         handler     : function()
         {
            this.up('ampleharvest-objects-search-panel-csearch').fireEvent(
                        AmpleHarvest.eventHandler.cWindowEvents.C_STR_EVENT_SAVED_QUERY_ADD,
                        this.ownerCt.ownerCt.get_JsonQuery(),
                        this.m_str_SourceGUID
                  );
         }
      }
      );

      
      //Check to see if a user can save a query
      this.m_bool_CanSave = true; //cPermissions::C_STR_PERMISION_SAVED_QUERY_ADD

      if (this.m_bool_CanSave > 0)
      {
         this.buttons.push(this.m_obj_Save_Query);
      }
      
      //Create next two default buttons
      this.buttons.push(
         Ext.create("Ext.button.Button",
         {
            text  : "Reset",
            handler  : function()
            {
               this.ownerCt.ownerCt.reset_Query();
            },
            scope : obj_This
         }), 
         Ext.create("Ext.button.Button",
         {
            text  : "Search",
            handler  : function()
            {
               this.enableBubble('do_Search');
               this.fireEvent("do_Search", this.get_QueryObject());
               //this.ownerCt.ownerCt.do_Search();
            },
            scope : obj_This
         })
      );

      this.callParent();

      this.on('afterrender', this.afterrender, this);

      this.on("beforestaterestore", function(obj_This, obj_State, obj_Opts)
            {
               m_obj_AmpleHarvest_ViewPort.g_obj_RestStateProvider.add_StateObject(this.stateId, this);
            }, this
      );
   },
   
   afterrender : function()
   {
      //I believe this is only used with saved searches
      if (this.ownerCt.ownerCt.json.json)
      {
         console.log(this.ownerCt.ownerCt.json.json);
         if (this.ownerCt.ownerCt.load_Query(this.ownerCt.ownerCt.json.json))
         {
            this.ownerCt.ownerCt.do_Search();
         }
      }
      var obj_Map = Ext.create('Ext.util.KeyMap', this.getEl(),
            {
               key      :
               [
                     10, 13
               ],
               fn    : function()
               {
                  this.ownerCt.ownerCt.do_Search();
               },
               scope : this
            });
   },

   reset          : function()
   {
      this.deactivateSaveQuery();
      this.set_CurQuery("*:*");
      this.getForm().reset();
   },

   setForm           : function(obj_Form)
   {
      this.removeAll(true);

      for (int_I = 0; int_I < obj_Form.items.length; int_I++)
      {
         var obj_Item = obj_Form.items[int_I];
         this.add(obj_Item);
      }

      if (obj_Form.load_FromJson)
      {
         this.load_FromJson = obj_Form.load_FromJson;
      }

      if (obj_Form.m_arr_StateEvents)
      {
         this.addStateEvents(obj_Form.m_arr_StateEvents);
      }

      if (obj_Form.height)
      {
         //this.up('ampleharvest-objects-search-panel-csearch').minHeight = obj_Form.height;
      }
   },

   search_Cmp        : function(obj_Cmp, str_Name)
   {
      if (obj_Cmp.items)
      {
         for (var I = 0; I < obj_Cmp.items.items.length; I++)
         {
            var obj_Return = this.search_Cmp(obj_Cmp.items.items[I],
                  str_Name
            );
            if (obj_Return)
            {
               return obj_Return;
            }
         }
      }
      if (obj_Cmp.name == str_Name)
      {
         return obj_Cmp;
      }

      return false;
   },

   set_FieldValue    : function(str_Name, str_Value)
   {
      var arr_Items = this.items.items;

      for (int_I = 0; int_I < arr_Items.length; int_I++)
      {
         var obj_Return = this.search_Cmp(arr_Items[int_I], str_Name);

         if (obj_Return)
         {
            if (obj_Return.store)
            {
               obj_Return.inputEl.dom.value = str_Value;
            }
            else
            {
               obj_Return.setValue(str_Value);
            }
            return true;
         }
      }
      return false;
   },

   get_QueryObject      : function()
   {
      // var obj_Temp = new Object();

      var arr_Query = new Array();

      var obj_Tmp = new Object();
      var obj_Form = this.getForm().getFields();

      for (int_I in obj_Form.items)
      {
         obj_Tmp = new Object();

         var obj_Item = obj_Form.items[int_I];
         var key = obj_Item.name;

         if (!obj_Item.getValue())
         {
            continue;
         }

         if (obj_Item)
         {
            obj_Tmp.dataType = obj_Item.dataType;
            obj_Tmp.type = "condition";
            obj_Tmp.condition = "==";
            obj_Tmp.join = "AND";
            obj_Tmp.property = key;

            if (key == "read")
            {

               if (obj_Item.getValue() == "unread")
               {
                  obj_Tmp.condition = '!=';
               }

               obj_Tmp.value = obj_config.user.userName;

            }
            else if ((key.substr(key.length - 5).toLowerCase()) == "start")
            {
               obj_Tmp.property = key.substr(0, key.length - 6);
               var str_EndValue = this.getForm().findField(key.substr(0,
                     key.length - 5
               )
                     + "end").getValue();
               if (str_EndValue)
               {
                  obj_Tmp.value_end = str_EndValue;
               }
               else
               {
                  obj_Tmp.value_end = "*";
               }

               obj_Tmp.value = obj_Item.getValue();
            }
            else if ((key.substr(key.length - 3).toLowerCase()) == "end")
            {
               obj_Tmp.property = key.substr(0, key.length - 4);
               var str_StartValue = this.getForm().findField(key.substr(0,
                     key.length - 3
               )
                     + "start").getValue();

               if (str_StartValue)
               {
                  continue;
               }

               obj_Tmp.value = "*";
               obj_Tmp.value_end = obj_Item.getValue();
            }
            else
            {
               obj_Tmp.value = obj_Item.getValue();
            }

            arr_Query.push(obj_Tmp);
         }
      }

      // obj_Temp.Query = arr_Query;
      return arr_Query;
   },

   activateSaveQuery : function()
   {
      this.m_obj_Save_Query.enable();
   },

   deactivateSaveQuery  : function()
   {
      this.m_obj_Save_Query.disable();
   },

   load_Query        : function(str_Data)
   {
      // alert("Load Data - "+str_Data);
      try
      {
         this.load_FromJson(Ext.decode(str_Data));
      }
      catch (e)
      {
         Ext.Msg.alert('Error', 'Failed to load your Query<br/>' + e);
         return false;
      }
      return true;
   },

   load_FromJson     : function(obj_Json)
   {
      alert("Default Load From Json");
   },

   set_CurQuery      : function(str_Query)
   {
      this.m_str_CurQuery = str_Query;
      var arr_Data = this.query("[m_str_BaseQuery]");

      for (var I = 0; I < arr_Data.length; I++)
      {
         arr_Data[I].m_str_BaseQuery = this.m_str_CurQuery;
      }

      // obj_Item.m_str_BaseQuery = this.m_str_CurQuery;
   },

   getState       : function()
   {
      var obj_State = this.callParent();

      // obj_State.m_arr_Items = [];

      if (this.items)
      {
         this.items.each(function(obj_Item, int_Index, int_Length)
               {
                  if (!this.m_arr_Items)
                  {
                     this.m_arr_Items = {};
                  }
                  if (obj_Item.getStateId())
                  {
                     this.m_arr_Items[obj_Item.getStateId()] = obj_Item
                           .getState();
                  }
               }, obj_State);
      }

      return obj_State;
   },

   applyState        : function(obj_State)
   {
      if (obj_State)
      {
         Ext.apply(this, obj_State);
         if (obj_State.m_arr_Items)
         {
            this.items.each(function(obj_Item, int_Index, int_Length)
                  {
                     if (obj_Item.getStateId())
                     {
                        var obj_State = this[obj_Item.getStateId()];
                        if (obj_State)
                        {
                           if (obj_State.collapsed)
                           {
                              console.log("collapse");
                              obj_Item.collapse();
                           }
                           Ext.apply(obj_Item, obj_State);
                        }
                     }
                  }, obj_State.m_arr_Items);
         }
      }
   },

   save_State        : function()
   {
      // console.log(this.state);
      Ext.state.Manager.set(this.getStateId(), this.getState());
      // alert("Test Save_State 1");
      // this.savePropToState(this.stateId,this.getState());
   }
}
);